import React from 'react'
import {
  View,
  StyleSheet,
  Text,
  Linking,
  Keyboard,
  LayoutAnimation
} from 'react-native'
import { ScaleS, ScaleT, IS_IPHONEX, IS_IOS } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import IMController from 'src/utils/IMController'
import {
  saveChatInfoRequest,
  pushMsgImRequest, talentTalk
} from 'src/utils/RequestAPI'
import DialogueComponent from 'src/pageP/message/chat-page/commponents/DialogueComponent'
import SendComponent from 'src/pageP/message/chat-page/commponents/SendComponent'
import CommonWordComponent from 'src/pageP/message/chat-page/commponents/CommonWordComponent'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { showModal } from 'src/utils/ModalUtil'
import ChatOptionModal from 'src/components/modal/ChatOptionModal'
import BasicChooseModal from 'src/components/modal/BasicChooseModal'
import { openAlums, openCamera } from 'src/utils/ImagePickerUtil'

const usefulExpressionsIH = ScaleS(55)
const usefulExpressionsH = ScaleS(usefulExpressionsIH * 4)
const paddingBottomX = IS_IPHONEX ? 30 : 10

export default class ChatPage extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: { headerBg: '#fff' },
      friendInfo: {},
      loginInfoState: {},
      title: '',
      value: '',
      lastMsgTime: 0, // 第一次拉取好友历史消息时，必须传0
      complete: false,
      maxCnt: 100,
      getMsgArr: false,
      sendValue: '',
      pnyin: '',
      sendStatus: false,
      scrollViewHeight: 0,
      historyStatus: false,
      listHeight: 0,
      paddingBottom: ScaleS(paddingBottomX),
      commonShow: false,
      clickQuickSend: false, // 快捷短语是否点击
      isScrollClick: false,
      commonModalShow: false, // 新增常用语弹框是否显示
      cardShow: true,
      keyboardShow: false,
      canCallPhone: false // 能否打电话
    }
    this.scrollY = 0
    this.getUserId = this.getUserId.bind(this)
    this.getSelToID = this.getSelToID.bind(this)
    this.getName = this.getName.bind(this)
    this.renderHeader = this.renderHeader.bind(this)
    this.activeSendMessage = this.activeSendMessage.bind(this)
  }

  childRender () {
    const { msgArray = [] } = this.props
    const {
      loginInfoState,
      friendInfo,
      commonShow,
      paddingBottom,
      keyboardShow,
      canCallPhone
    } = this.state
    return (
      <View style={styles.faContainer}>
        {this.renderHeader()}
        <DialogueComponent
          style={styles.container}
          onLayout={this.onScrollViewLayout}
          friendInfo={friendInfo}
          loginInfoState={loginInfoState}
          msgArray={msgArray}
          onContentSizeChange={this.onContentSizeChange}
          onScroll={this.onScroll}
          onTouchEnd={this.onTouchEnd}
          onTouchMove={this.onTouchMove}
          onTouchStart={this.onTouchStart}
          scrollViewRef={this._scrollViewRef}
          isPageB={this.isPageB}
          userId={this.getUserId()}
          selToID={parseInt(this.getSelToID())}
        />
        <View style={styles.bottomContainer}>
          <SendComponent
            paddingBottom={paddingBottom}
            placeholder={'请输入...'}
            onCallPress={this.onCall}
            onMoreOptionPress={this._moreOption}
            onCommonWordPress={this.onQuickSend}
            textInputRef={this._textInputRef}
            onSubmitEditing={this.sendMsg}
            canCallPhone={canCallPhone}
            keyboardShow={keyboardShow}/>
          {!!commonShow && (
            <CommonWordComponent
              isPageB={this.isPageB}
              userId={this.getUserId()}
              itemPress={this.sendCommonMsg}
              commonModalShow={this.commonModalShow}
              addCommonWord={this._addCommonWord}
              onCancel={this._onCancel}
            />
          )}
        </View>
      </View>
    )
  }

  renderHeader () {

  }

  getSelToID () {
    return this.props.selToID
  }

  _scrollViewRef = (ref) => {
    this.scrollView = ref
  }

  _textInputRef = (ref) => {
    this.textInputRef = ref
  }

  /**
   * 点击添加常用语
   * @private
   */
  _addCommonWord = () => {
    this.isShowUsefulExpressions = true
  }

  /**
   * 取消编辑
   * @private
   */
  _onCancel = () => {
    this.isShowUsefulExpressions = false
    this.commonModalShow(false)
  }

  renderNavigationBarChild = () => {
    const { title } = this.state
    return <Text>{title}</Text>
  }

  componentWillMount () {
    this.setState({ paddingBottom: ScaleS(paddingBottomX) })
  }

  componentDidMount () {
    this.onShow()
    if (IS_IOS) {
      this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow)
      this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide)
    } else {
      this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow)
      this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide)
    }
  }

  componentDidUpdate (prevProps, prevState) {
    if (prevProps.msgArray && prevProps.msgArray.length && this.state.complete) {
      if (prevProps.msgArray.length !== this.props.msgArray.length) {
        this.setState({
          canCallPhone: this.judgeCanCallPhone(this.props.msgArray)
        })
        setTimeout(() => {
          this.scrollView.scrollTo({ y: this.scrollY, animated: false })
        }, 50)
      }
    }
    return null
  }

  /**
   * 获取userId
   */
  getUserId () {

  }

  componentWillUnmount () {
    super.componentWillUnmount()
    if (IS_IOS) {
      this.keyboardWillShowListener.remove()
      this.keyboardWillHideListener.remove()
    } else {
      this.keyboardDidShowListener.remove()
      this.keyboardDidHideListener.remove()
    }
  }

  _keyboardWillShow = (event) => {
    const { commonModalShow } = this.state
    const height = event.endCoordinates.height
    this.layoutAnimation()
    !commonModalShow && this._keyboardShow(Math.abs(height) + ScaleS(10))
  }

  _keyboardDidShow = (event) => {
    const { commonModalShow } = this.state
    !commonModalShow && this._keyboardShow(ScaleS(10))
  }

  /**
   * 键盘显示
   * @param paddingBottom
   * @private
   */
  _keyboardShow = (paddingBottom) => {
    if (this.isShowUsefulExpressions) return
    this.setState({
      paddingBottom,
      cardShow: false,
      commonShow: false,
      clickQuickSend: false,
      keyboardShow: true
    })
    // 弹出后 定位scrollview位置
    setTimeout(() => {
      if (this && this.scrollView) {
        this.scrollView.scrollToEnd({ animated: true })
      }
    }, 50)
  }

  _keyboardWillHide = () => {
    const { clickQuickSend, commonModalShow } = this.state
    if (!clickQuickSend && !commonModalShow) {
      this.layoutAnimation()
      this.setState({
        paddingBottom: ScaleS(paddingBottomX),
        commonShow: false,
        clickQuickSend: false,
        keyboardShow: false
      })
      // 弹出后 定位scrollview位置
      setTimeout(() => {
        // this.setState({
        //   cardShow: true
        // }, () => {
        if (this.scrollView) {
          this.scrollView.scrollToEnd({ animated: false })
        }
        // })
      }, 50)
    }
  }

  _keyboardDidHide = () => {
    const { clickQuickSend, commonModalShow } = this.state
    if (!clickQuickSend && !commonModalShow) {
      this.layoutAnimation()
      this.setState({
        paddingBottom: ScaleS(paddingBottomX),
        commonShow: false,
        clickQuickSend: false
      })
      // 弹出后 定位scrollview位置
      setTimeout(() => {
        // this.setState({
        //   cardShow: true
        // }, () => {
        if (this.scrollView) {
          this.scrollView.scrollToEnd({ animated: false })
        }
        // })
      }, 50)
    }
  }

  layoutAnimation = () => {
    // 动画
    IS_IOS && LayoutAnimation.configureNext({
      duration: 220,
      create: {
        type: LayoutAnimation.Types.linear,
        property: LayoutAnimation.Properties.opacity
      },
      update: {
        type: LayoutAnimation.Types.easeInEaseOut
        // type: LayoutAnimation.Types.linear
      }
    })
  }

  onScroll = event => {
    // 垂直滚动距离
    this.scrollY = event.nativeEvent.contentOffset.y
    if (!this.scrollY) {
      this.getHistoryMsgs()
    }
  }

  commonModalShow = flag => {
    this.setState({
      commonModalShow: flag
    })
  }

  onContentSizeChange = (contentWidth, contentHeight) => {
    // const { listHeight } = this.state
    // const height = contentHeight - listHeight
    // this.scrollView.scrollTo({ y: height, animated: false })
    // this.setState({ listHeight: contentHeight })
  }

  onScrollViewLayout = e => {
    const height = e.nativeEvent.layout.height
    this.setState({ scrollViewHeight: height })
  }

  onShow = () => {
    // 获取聊天记录
    const { selToID, loginInfo } = this.props
    ShowLoading()
    // 获取两个人的信息
    IMController.getUsers([selToID, loginInfo.accid]).then(data => {
      if (data.length) {
        const friendInfo = data[0]
        const loginInfoState = data[1]
        this.setState({
          friendInfo,
          loginInfoState,
          title: friendInfo.nick
        })
        this.getHistoryMsgs()
      }
    })
  }

  getHistoryMsgs = () => {
    return new Promise(resolve => {
      const { lastMsgTime, maxCnt, complete } = this.state
      const { selToID, msgArray } = this.props
      if (!complete) {
        IMController.getHistoryMsgs({ selToID, maxCnt, lastMsgTime }).then(
          ({ obj, complete: isComplete }) => {
            const newMsgArray = [...obj.msgs, ...msgArray]
            this.props.updateImState({
              msgArray: newMsgArray
            })
            console.info(newMsgArray, 'newMsgArraynewMsgArraynewMsgArray')
            this.activeSendMessage(newMsgArray.length < 1)
            this.setState({
              complete: isComplete,
              lastMsgTime:
                (obj.msgs[0] && obj.msgs[0].time) || new Date().getTime(),
              getMsgArr: true,
              canCallPhone: this.judgeCanCallPhone(newMsgArray)
            })
            if (!isComplete) {
              this.getHistoryMsgs()
            } else {
              const timer = setTimeout(() => {
                clearTimeout(timer)
                if (this && this.scrollView) {
                  this.scrollView.scrollToEnd({ animated: false })
                }
              }, 50)
            }
            resolve()
          }
        )
      }
    })
  }

  // scrollview 触顶后 获取历史消息
  onScrollToUpper = () => {
    // 继续获取历史消息
    // const { historyStatus } = this.state
    // if (!historyStatus) {
    //   this.setState({
    //     historyStatus: true
    //   })
    //   const { complete } = this.state
    //   if (!complete) {
    //     this.getHistoryMsgs(true).then(() => {
    //       this.setState({
    //         historyStatus: false
    //       })
    //     })
    //   }
    // } else {
    // }
  }

  judgeCanCallPhone = (msgArray) => {
    // 判断是否两人都发送过消息 true： 可打电话
    const { selToID, loginInfo: { accid } } = this.props
    let isFrom = false // 别人主动发
    let isTo = false // 自己主动发
    let flag = false
    msgArray.map(item => {
      if (item.from === selToID && item.to === accid) {
        isFrom = true
      }
      if (item.to === selToID && item.from === accid) {
        isTo = true
      }
      if (isFrom && isTo) {
        flag = true
      }
    })
    return flag
  }

  activeSendMessage () {
    // 如果没有发过消息 则主动发消息
  }

  sendMsg = (value) => {
    // 发送消息
    return new Promise(resolve => {
      const { sendStatus } = this.state
      if (!sendStatus) {
        this.setState({
          sendStatus: true
        })
        const selToID = this.getSelToID()
        IMController.sendMsg({ selToID, value }).then((sendSuccess) => {
          this.setState({
            sendValue: '',
            sendStatus: false
          })
          resolve(true)
          if (sendSuccess) {
            // 滚动的底部
            const timer = setTimeout(() => {
              clearTimeout(timer)
              if (this && this.scrollView) {
                this.scrollView.scrollToEnd({ animated: false })
              }
            }, 50)

            // 推送
            pushMsgImRequest({
              params: {
                alia: `${this.isPageB ? 'c' : 'b'}_${parseInt(selToID)}`,
                name: this.getName(),
                content: value
              }
            })
            this._talentTalk()
          } else {
            CommonToast('发送消息失败，请重新发送')
          }
        })
      } else {
        resolve(false)
      }
    })
  }

  _talentTalk = () => {
    const { userinfo: { userId } } = this.props
    if (this.isPageB) {
      const { personItem: { userId: userIdC } } = this.state
      const { company, navigation: { state: { params: { postId } = {} } } } = this.props
      company && company.companyId && talentTalk({
        params: {
          type: 'B',
          cmpUserId: userIdC,
          companyId: company.companyId,
          userId: userId,
          postId
        }
      }).finally(() => {
      })
    } else {
      const { jobItem } = this.state
      if (jobItem && jobItem.boss && jobItem.boss.companyId) {
        const { jobItem: { boss: { companyId = '', userId: userIdB }, id: postId } } = this.state
        talentTalk({
          params: {
            type: 'C',
            cmpUserId: userId,
            postId: postId,
            companyId,
            userId: userIdB
          }
        })
      }
    }
  }

  getName () {

  }

  /**
   * 发送常用语
   * @param item
   */
  sendCommonMsg = item => {
    const value = item.commonLanguage
    // 发送快捷语
    console.log('sendCommonMsg', value)
    const { sendStatus } = this.state

    if (!sendStatus) {
      this.setState({
        sendStatus: true
      })
      const selToID = this.getSelToID()
      IMController.sendMsg({ selToID, value }).then(() => {
        this.setState({
          sendValue: '',
          sendStatus: false
        })
        // 滚动的底部
        const timer = setTimeout(() => {
          clearTimeout(timer)
          // 收起快捷语
          this.onQuickSend()
        }, 100)
      })
      // 记录用户聊天信息
      // this.saveChatInfo()
      // 推送
      pushMsgImRequest({
        params: {
          alia: `${this.isPageB ? 'c' : 'b'}_${parseInt(selToID)}`,
          name: this.getName(),
          content: value
        }
      })
      this._talentTalk()
    }
  }

  saveChatInfo = () => {
    // 记录聊天发起信息
    const {
      userinfo: { role, companyId }
    } = this.props
    const {
      friendInfo: { account: accountFriend, custom = '{}' },
      loginInfoState: { account: accountLogin }
    } = this.state
    const exInfo = JSON.parse(custom)
    const data = {
      cmpUserId:
        role === 'C' ? parseInt(accountFriend) : parseInt(accountLogin),
      companyId: (role === 'C' ? exInfo.companyId : companyId) || '',
      createdBy: parseInt(accountLogin),
      userId: role === 'C' ? parseInt(accountLogin) : parseInt(accountFriend)
    }
    saveChatInfoRequest(data)
  }

  onCall = () => {
    this.optionModel.close()
    const {
      friendInfo: { tel },
      canCallPhone
    } = this.state
    if (canCallPhone) {
      return Linking.openURL(`tel:${tel}`)
    } else {
      CommonToast('只有双方沟通过才能打电话')
    }
  }

  onQuickSend = () => {
    Keyboard.dismiss()
    const { commonShow } = this.state
    const commonHeight = this.calcCommonBottom()
    if (commonShow) {
      this.layoutAnimation()
      this.setState({
        paddingBottom: ScaleS(paddingBottomX),
        commonShow: false,
        clickQuickSend: true
        // cardShow: true
      })
      // 弹出后 定位scrollview位置
      setTimeout(() => {
        if (this && this.scrollView) {
          this.scrollView.scrollToEnd({ animated: false })
        }
      }, 50)
    } else {
      this.layoutAnimation()
      this.setState({
        paddingBottom: ScaleS(10 + Math.abs(commonHeight)),
        commonShow: true,
        clickQuickSend: true,
        cardShow: false
      })
      // 弹出后 定位scrollview位置
      setTimeout(() => {
        if (this && this.scrollView) {
          this.scrollView.scrollToEnd({ animated: true })
        }
      }, 50)
    }
  }

  _moreOption = () => {
    // 点击更多 弹框
    const { canCallPhone } = this.state
    this.optionModel = showModal(
      <ChatOptionModal
        canCallPhone={canCallPhone}
        onCall={this.onCall}
        onShowImgOption={this._showImgOption}
      />
    )
  }

  onTouchStart = () => {
    // scrollview 触摸开始事件
    const { commonShow } = this.state
    this.layoutAnimation()
    if (commonShow) {
      // 点击scrollview  隐藏掉常用语
      Keyboard.dismiss()
      this.setState({
        paddingBottom: ScaleS(paddingBottomX),
        commonShow: false,
        clickQuickSend: true
      })
    }
    this.setState({
      // cardShow: true,
      keyboardShow: false
    })
    this.textInputRef.blur()
  }

  onTouchMove = () => {
    // scrollview 触摸移动事件
  }

  onTouchEnd = () => {
    // scrollview 触摸结束事件
  }

  calcCommonBottom = () => {
    // return -usefulExpressionsH + 160 - ScaleS(56)
    return 0
  }

  _showImgOption = () => {
    // 显示图片操作弹窗
    this.optionModel.close()
    this.imgOptionModel = showModal(
      <BasicChooseModal
        topText='拍摄'
        topFunc={this._cameraSelect}
        middleText='相册'
        middleFunc={this._albumsSelect}
        bottomText='取消'
        bottomFunc={() => this.imgOptionModel.colse()}
      />
    )
  }

  _albumsSelect = () => {
    // 发送图片消息 - 相册
    this.imgOptionModel.close()
    openAlums().then(image => {
      ShowLoading()
      this._imSendImg(image)
    })
  }

  _cameraSelect = () => {
    // 发送图片消息 - 拍照
    this.imgOptionModel.close()
    openCamera().then(image => {
      ShowLoading()
      this._imSendImg(image)
    })
  }

  _imSendImg = (image) => {
    return new Promise(resolve => {
      const selToID = this.getSelToID()
      IMController.sendImage({
        image,
        selToID
      }).then(imgSuccess => {
        this.setState({
          sendValue: '',
          sendStatus: false
        })
        DismissLoading()
        resolve(true)
        if (imgSuccess) {
        // 滚动的底部
          const timer = setTimeout(() => {
            clearTimeout(timer)
            if (this.scrollView) {
              this.scrollView.scrollToEnd({ animated: false })
            }
          }, 50)

          // 推送
          pushMsgImRequest({
            params: {
              alia: `${this.isPageB ? 'c' : 'b'}_${parseInt(selToID)}`,
              name: this.getName(),
              content: '您收到一张图片'
            }
          })
          this._talentTalk()
        } else {
          CommonToast('发送消息失败，请重新发送')
        }
      })
    })
  }
}

const styles = StyleSheet.create({
  faContainer: {
    flex: 1,
    backgroundColor: '#F9FAFA'
  },
  container: {
    flex: 1,
    paddingVertical: ScaleS(20),
    paddingHorizontal: ScaleS(20)
  },
  headerImg: {
    width: ScaleS(52),
    height: ScaleS(52),
    borderRadius: ScaleS(26),
    marginRight: ScaleS(14),
    // backgroundColor: '#cccccc',
    resizeMode: 'cover'
  },
  headerImgRight: {
    marginRight: 0,
    marginLeft: ScaleS(14)
  },
  chatContainer: {
    flexDirection: 'column',
    marginBottom: ScaleS(30)
  },
  chatTimeContent: {
    flexDirection: 'row',
    justifyContent: 'center',
    textAlign: 'center',
    marginBottom: ScaleS(30)
  },
  chatTime: {
    fontSize: ScaleT(14),
    color: '#d1d1d1'
  },
  chatItem: {
    flexDirection: 'row',
    alignItems: 'center'
    // width: ScaleS(375)
  },
  chatItemOther: {
    justifyContent: 'flex-start'
  },
  chatItemMine: {
    justifyContent: 'flex-end'
  },
  chatValue: {
    maxWidth: ScaleS(243),
    backgroundColor: '#fff',
    borderRadius: ScaleS(15),
    paddingVertical: ScaleS(12),
    paddingHorizontal: ScaleS(16)
  },
  chatValueRight: {
    backgroundColor: '#92E7BC'
  },
  chatItemText: {
    fontSize: ScaleT(14),
    color: '#444444'
  },
  arrow: {
    position: 'absolute',
    left: ScaleS(-10),
    top: '50%',
    transform: [{ translateY: -22 }],
    marginTop: 20,
    width: 0,
    height: 0,
    borderTopWidth: ScaleS(10),
    borderTopColor: 'transparent',
    borderRightWidth: ScaleS(20),
    borderRightColor: 'white',
    borderBottomWidth: ScaleS(10),
    borderBottomColor: 'transparent'
  },
  arrowRight: {
    position: 'absolute',
    right: ScaleS(-10),
    top: '50%',
    // transform: [{ translateY: -22 }],
    width: 0,
    height: 0,
    borderTopWidth: ScaleS(10),
    borderTopColor: 'transparent',
    borderLeftWidth: ScaleS(20),
    borderLeftColor: '#92E7BC',
    borderBottomWidth: ScaleS(10),
    borderBottomColor: 'transparent'
  },
  bottomContainer: {},
  sendContainer: {
    width: ScaleS(375),
    paddingHorizontal: ScaleS(10),
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F3F3F3',
    paddingBottom: ScaleS(paddingBottomX)
  },
  commonIcon: {
    width: ScaleS(54),
    height: ScaleS(30),
    borderRadius: ScaleS(3),
    justifyContent: 'center',
    alignItems: 'center'
  },
  commonIconText: {
    color: '#fff',
    fontSize: ScaleT(14)
  },
  quickIcon: {
    width: ScaleS(30),
    height: ScaleS(30)
  },
  inputContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    height: ScaleS(40),
    borderRadius: ScaleS(20),
    backgroundColor: '#fff',
    marginHorizontal: ScaleS(12)
  },
  input: {
    flex: 1,
    height: ScaleS(40),
    backgroundColor: '#fff',
    borderRadius: ScaleS(20),
    marginHorizontal: ScaleS(10)
  },
  commonContainer: {
    backgroundColor: '#ffffff'
  },
  commonContainerX: {
    paddingBottom: ScaleS(30)
  },
  commonList: {
    height: usefulExpressionsH
  },
  commonItem: {
    height: usefulExpressionsIH
  },
  deleteTextImg: {
    width: ScaleS(20),
    height: ScaleS(20),
    backgroundColor: 'red'
  },
  commonText: {
    fontSize: ScaleT(15),
    color: '#666666'
  },
  commonEditImg: {
    width: ScaleS(13),
    height: ScaleS(13),
    backgroundColor: 'yellow'
  },
  commonSortImg: {
    width: ScaleS(13),
    height: ScaleS(13),
    backgroundColor: 'blue'
  },
  commonWordAddView: {
    height: ScaleS(56),
    alignItems: 'center',
    justifyContent: 'center'
  },
  commonSettingView: {
    position: 'absolute',
    left: 0,
    top: 0,
    bottom: 0,
    width: ScaleS(56),
    alignItems: 'center',
    justifyContent: 'center'
  },
  commonSettingImg: {
    width: ScaleS(32),
    height: ScaleS(32),
    backgroundColor: 'red'
  },
  commonWordTextView: {
    flexDirection: 'row',
    alignItems: 'flex-start'
  },
  commonWordText: {
    color: '#62D2A7',
    fontSize: ScaleT(16),
    fontWeight: '500'
  },
  commonWordTextSymbol: {
    top: ScaleS(-8),
    position: 'absolute'
  }
})
